<template>
    <div>
        <!-- 头部面包屑导航区域 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home ' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数管理</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片视图 -->
        <el-card>
            <!-- 提示框 -->
            <el-alert title="注意 : 只允许为三级分类设置相关参数" type="warning" :closable="false" show-icon>
            </el-alert>
            <el-row class="catpoy">
                <!-- 选择商品分类区 -->
                <el-col>选择商品分类区 :</el-col>
                <!-- 选择商品分类的级联框 -->
                <el-cascader v-model="selectCateKeys" :options="CateList" expand-trigger="hover" :show-all-levels="false"
                    :props="cateProps" @change="handleChange"></el-cascader>
            </el-row>
            <!-- Teables 标签页 -->
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <!-- 添加动参数面板 -->
                <el-tab-pane label="动态参数" name="many">
                    <!-- 添加参数的按钮 -->
                    <el-button type="primary" size="mini" :disabled="isButton"
                        @click="addDialogVisible = true">动态参数</el-button>
                    <!-- 动态参数的数据 -->
                    <el-table :data="manytabdata" border style="width: 100%">
                        <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag :key="index" v-for="(itme, index) in scope.row.attr_vals" closable
                                    :disable-transitions="false" @close="handleClose(index,scope.row)">
                                    {{ itme }}
                                </el-tag>
                                <!-- 添加 el-tag 标签 -->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput"
                                    size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="inputshow(scope.row)">new_value</el-button>
                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type="index"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称">
                        </el-table-column>
                        <el-table-column prop="name" label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini"
                                    @click="DataEdit(scope.row.attr_id), EditDialogVisible = true">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini"
                                    @click="Delete(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 添加静态属性面板 -->
                <el-tab-pane label="静态属性" name="only">
                    <!-- 添加属性的按钮 -->
                    <el-button type="primary" size="mini" :disabled="isButton"
                        @click="addDialogVisible = true">静态属性</el-button>
                    <!-- 静态参数 -->
                    <el-table :data="onlytabdata" border style="width: 100%">
                        <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag :key="index" v-for="(itme, index) in scope.row.attr_vals" closable
                                    :disable-transitions="false" @close="handleClose(index,scope.row)">
                                    {{ itme }}
                                </el-tag>
                                <!-- 添加 el-tag 标签 -->
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput"
                                    size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="inputshow(scope.row)">new_value</el-button>
                            </template>
                        </el-table-column>
                        <!-- 索引列 -->
                        <el-table-column type="index"></el-table-column>
                        <el-table-column prop="attr_name" label="属性名称">
                        </el-table-column>
                        <el-table-column prop="name" label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini"
                                    @click="DataEdit(scope.row.attr_id), EditDialogVisible = true">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini"
                                    @click="Delete(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!-- 添加参数的对话框 -->
        <el-dialog :title="'添加' + titleText" :visible.sync="addDialogVisible" width="50%">
            <el-form ref="form" :model="addForm" :rules="addFormRules" label-width="80px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addDialogParams">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 修改参数的对话框 -->
        <el-dialog :title="'修改' + titleText" :visible.sync="EditDialogVisible" width="50%">
            <el-form ref="EditFormRef" :model="EditForm" :rules="EditFormRules" label-width="80px">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="EditForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="EditDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="EditDialogParams">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分了列表
      CateList: [],
      // 配置级联选择的配偶
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 这是级联选择框的双向绑定数组
      selectCateKeys: [],
      // 被激活的页签的名称
      activeName: 'many',
      // 动态参数的数据
      manytabdata: [],
      // 静态参数的数据
      onlytabdata: [],
      // 控制添加对话框的显示
      addDialogVisible: false,
      // 定义修改参数对话框
      EditDialogVisible: false,
      // 绑定添加表单数据
      addForm: {
        attr_name: ''
      },
      // 绑定修改表单中的数据
      EditForm: {
        attr_name: ''
      },
      // 保存要修改的id
      attr_id: 0,
      // 表单验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 修改表单验证规则
      EditFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }

    }
  },
  created() {
    this.getCateList()
  },
  computed: {
    // 如果按钮需要被禁用则返回 true 否则返回 false
    isButton() {
      if (this.selectCateKeys.length !== 3) {
        return true
      };
      return false
    },
    // 当前选中的三级分类的id
    cateId() {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[2]
      }
      return null
    },
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态参数'
      }
    }
  },
  methods: {
    // 获取所有的商品列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.erroe('获取失败')
      this.CateList = res.data
      console.log(this.CateList)
    },
    // 级联选择框中选择项发生变化 会触发这个函数
    handleChange() {
      this.getParamsDate()
    },
    async getParamsDate() {
      console.log()
      // 证明选中的不是三级分类
      if (this.selectCateKeys.length !== 3) {
        this.selectCateKeys = []
        return
      }
      // 根据所选择的分类的id 和当前所处的面板 获取对应的参数
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.$message.success('获取成功')
      console.log(res)
      res.data.forEach(itme => {
        itme.attr_vals = itme.attr_vals ? itme.attr_vals.split(' ') : []
        itme.inputVisible = false
        itme.inputValue = ''
      })
      console.log(res)
      if (this.activeName === 'many') {
        this.manytabdata = res.data
      } else {
        this.onlytabdata = res.data
      }
    },
    // Tab 页签点击事件的处理函数
    handleClick() {
      this.getParamsDate()
    },
    // 确定添加按钮
    async addDialogParams() {
      const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
        attr_name: this.addForm.attr_name,
        attr_sel: this.activeName
      })
      if (res.meta.status !== 201) return this.$message.error('创建失败')
      this.$message.success('创建成功')
      this.addDialogVisible = false,
      this.getParamsDate()
    },
    async Delete(id) {
      const confirm = await this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirm !== 'confirm') return this.$message.success('取消删除')
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      console.log(confirm)
      this.getParamsDate()
    },
    // 根据id查询要修改参数
    async DataEdit(attr_id) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`)
      if (res.meta.status !== 200) return
      this.EditForm.attr_name = res.data.attr_name
      this.attr_id = attr_id
    },
    // 修改参数
    EditDialogParams() {
      console.log(this.$refs)
      this.$refs.EditFormRef.validate(async (value) => {
        if (value) {
          const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.attr_id}`, {
            attr_name: this.EditForm.attr_name,
            attr_sel: this.activeName
          })
          if (res.meta.status !== 200) return this.$message.error('更新失败')
          this.$message.success('更新成功')
          this.getCateList()
          this.EditDialogVisible = false
        } else {
          this.$message.error('请输入参数')
        }
      })
    },
    // 点击显示input 输入框
    inputshow(scope) {
      scope.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus()
      })
    },
    // 添加 attr_value 失去焦点时触发
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.AllInputvalue(row)
    },
    async AllInputvalue(row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('参数添加失败')
      }
    },
    // 删除参数
    handleClose(id, row) {
      console.log(row)
      row.attr_vals.splice(id, 1)
      this.AllInputvalue(row)
    }
  }
}
</script>

<style lang="less" scoped>
.catpoy {
    margin: 15px 0;
}

.el-tag {
    margin: 5px 20px;
}
.input-new-tag{
    width: 90px !important;
    height: 35px !important;
}
.el-col{
    margin: 0 0 15px 0 !important;
}
</style>
